package com.milo.config;

import com.bstek.ureport.console.UReportServlet;
import com.bstek.ureport.definition.datasource.BuildinDatasource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @author milogenius
 * @date 2020-04-18 12:00
 */
@Configuration
@ImportResource("classpath:ureport-console-context.xml")
public class URreportConfig {

    @Value("${spring.datasource.driver-class-name}")
    String driverClass;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String userName;
    @Value("${spring.datasource.password}")
    String passWord;

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
         ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new UReportServlet());
        bean.addUrlMappings("/ureport/*");
         return bean;
    }

    @Bean(name = "systemDataSource")
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }

    /**
     * 内置数据源
     * @param dataSource
     * @return
     */
    @Bean
    public BuildinDatasource buildinDatasourceForSystem(final @Qualifier("systemDataSource") DataSource dataSource){
        return new BuildinDatasource() {

            @Override
            public String name() {
                return "支付宝生活号";
            }

            @Override
            public Connection getConnection() {
                try {
                    return dataSource.getConnection();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };

    }


}
